<template>
  <!-- 图片拖拽交换位置组件 -->
  <div
    class="imgItem"
    @dragstart="dragStartHandler"
    @dragover.prevent="dragOverHandler"
    @dragenter="dragEnterHandler"
    @dragend="dragEndHandler"
    :style="{
      width: imgWidth,
      height: imgHeight,
    }"
  >
    <img
      class="bgImg"
      :src="imgSrc"
      alt=""
      :width="imgWidth"
      :height="imgHeight"
    />
    <em class="imgClose" @click="removeImg"></em>
  </div>
</template>
<script>
export default {
  name: "dragImgItem",
  props: {
    //图片对应的下标
    index: {
      type: Number,
      required: true,
    },
    //图片回显的路径
    imgSrc: {
      type: String,
      required: true,
    },
    //图片回显的宽度
    imgWidth: {
      default: "150px",
    },
    //图片回显的高度
    imgHeight: {
      default: "150px",
    },
  },
  methods: {
    // 用户开始拖动元素时触发
    dragStartHandler() {
      this.$emit("setCurDragImg", this.index);
    },

    //用户完成元素拖动后触发
    dragEndHandler(e) {
      this.$emit("clearCurDragImg");
    },

    // 当某被拖动的对象在另一对象容器范围内拖动时触发此事件
    dragOverHandler(e) {
      e.dataTransfer.dropEffect = "move";
    },

    // 当被鼠标拖动的对象进入其容器范围内时触发此事件
    dragEnterHandler(e) {
      console.log("e", e);
      e.dataTransfer.effectAllowed = "move";
      this.$emit("dragImg", this.index);
    },

    //删除图片事件
    removeImg() {
      this.$emit("removeImg");
    },
  },
};
</script>
<style scoped lang="scss">
.imgItem {
  position: relative;
  height: 150px;
  width: 150px;
  display: inline-block;
  border-radius: 5px;
  float: left;
  margin: 0 15px 15px 0;
  .bgImg {
    height: 150px;
    width: 150px;
    object-fit: cover;
    border: 1px solid #dcdfe6;
    border-radius: 5px;
  }
  .imgClose {
    position: absolute;
    top: 0;
    right: 0;
    width: 30px;
    height: 30px;
    margin-top: -13px;
    margin-right: -13px;
    cursor: pointer;
    background: url("~@/assets/images/imgClose.png") top left
      no-repeat;
    background-size: cover;
  }
}
</style>
